package com.gxa.common;

import com.alibaba.fastjson.JSONObject;

import com.gxa.common.R.ResponseData;
import com.gxa.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token = request.getHeader("Authorization");
        ResponseData<Object> r = new ResponseData();
        response.setContentType("applcation/json;charset=utf-8");
        if (token == null || "".equals(token)){
            r.setCode(208);
            r.setMsg("请登录！");
            response.getWriter().write(JSONObject.toJSONString(r));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        if (JwtUtils.validateJwt(token).isSuccess()){
            //验证成功,允许访问其它接口
            return true;
        }
        //验证失败
        r.setCode(209);
        r.setMsg("token过期或错误！");
        response.getWriter().write(JSONObject.toJSONString(r));
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
